package cn.edu.javaweb.userServlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.javaweb.utils.DBUtil;

@WebServlet("/ForumEditorServlet")
public class ForumEditorServlet extends HttpServlet {
	DBUtil db;
	private static final long serialVersionUID = 1L;
    
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		//设置编码方式
	    request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");   //不设置会乱码
				
		//从ForumEditor.jsp中获取参数
		String topic=request.getParameter("topic");
		String part=request.getParameter("part");
		System.out.println(topic);
		System.out.println(part);
		
		//从Login.html获取id
		HttpSession session = request.getSession(true);     // 如果不存在 session 会话，则创建一个 session 对象
		String userid = session.getAttribute("id").toString();
		
		//JDBC连接数据库
		db = new DBUtil();  //调用构造函数，数据库的搭建
		String SQL = "insert into forum (topic,author,part) values ("+"'"+topic+"'"+","+userid+","+"'"+part+"'"+");";
		int result=db.update(SQL);  //调用（工具类）update方法，result来传递结果
		response.setContentType("text/html;charset=utf-8");
	    PrintWriter out=response.getWriter();
		if(result>0){
			out.println("<script language=javascript>alert('发布成功！');window.location='ForumServlet';</script>");
	    }else{
	    	out.println("<script language=javascript>alert('发布失败,请重新发布');window.location='ForumEditorServlet';</script>");
		}
	}
}
